<template>
  <div class="print-layout-wrapper">
    <el-space class="card mb5 tools" wrap>
      <div>
        <!-- 纸张大小 A3、A4 等 -->
        <el-button-group>
          <template v-for="(value, type) in paperTypes" :key="type">
            <el-button :color="curPaperType == type ? '#626aef' : ''" @click="setPaper(type, value)">
              {{ type }}
            </el-button>
          </template>
          <el-popover placement="bottom" trigger="click">
            <template #reference>
              <el-button :color="curPaperType == 'other' ? '#626aef' : ''" @click="showPaperPop">自定义纸张</el-button>
            </template>
            <div class="flex-col">
              <el-text type="primary">宽(mm):<el-input v-model="paperWidth" type="number" placeholder="宽(mm)" /></el-text>
              <el-text type="primary">高(mm):<el-input v-model="paperHeight" type="number" placeholder="高(mm)" /></el-text>
              <el-button class="primary circle-10" style="margin-top: 6px" @click.stop="setPaperOther">确定</el-button>
            </div>
          </el-popover>
        </el-button-group>
      </div>

      <div>
        <el-button-group>
          <el-button @click.stop="rotatePaper" :icon="Refresh"> 页面方向 </el-button>
          <el-button @click.stop="clearPaper" :icon="CircleClose"> 清空 </el-button>
          <el-button @click.stop="jsonView" :icon="View"> 查看JSON </el-button>
          <el-button @click.stop="jsonImport" :icon="Download"> 导入json</el-button>
          <el-button @click.stop="print" :icon="Printer"> 打印预览 </el-button>
        </el-button-group>
      </div>
      <div>
        <el-radio-group @change="setElsAlign">
          <el-radio-button value="left" title="左对齐">
            <i class="iconfont2 icon-zuoduiqi1" />
          </el-radio-button>
          <el-radio-button value="vertical" title="居中">
            <i class="iconfont2 icon-chuizhijuzhong-F" />
          </el-radio-button>
          <el-radio-button value="right" title="右对齐">
            <i class="iconfont2 icon-huaban1" />
          </el-radio-button>
          <el-radio-button value="top" title="顶部对齐">
            <i class="iconfont2 icon-dingbuduiqi1" />
          </el-radio-button>
          <el-radio-button value="horizontal" title="垂直居中">
            <i class="iconfont2 icon-chuizhijuzhongduiqi" />
          </el-radio-button>
          <el-radio-button value="bottom" title="底部对齐">
            <i class="iconfont2 icon-huaban" />
          </el-radio-button>
          <el-radio-button value="distributeHor" title="横向分散">
            <i class="iconfont2 icon-moduanzuoyouzhankai" />
          </el-radio-button>
          <el-radio-button value="distributeVer" title="纵向分散">
            <i class="iconfont2 icon-expand-vertical-line" />
          </el-radio-button>
        </el-radio-group>
      </div>

      <!-- 缩放 -->
      <div class="flx-align-center">
        <el-button @click="changeScale(false)" :icon="ZoomOut"></el-button>
        <div style="margin: 0 4px; width: 40px">{{ (scaleValue * 100).toFixed(0) }}%</div>
        <el-button @click="changeScale(true)" :icon="ZoomIn"></el-button>
      </div>

      <div>
        <el-button @click="handleSaveTemplate"> <i class="iconfont2 icon-baocun icons mr3"></i> 保存模板</el-button>
      </div>
    </el-space>
    <div class="splitpanes-box">
      <splitpanes>
        <pane size="12" class="card pane-box">
          <el-text tag="b" size="large">基础组件</el-text>
          <el-space fill wrap :fill-ratio="40" :direction="'horizontal'" class="mt20">
            <div class="ep-draggable-item item" tid="defaultModule.text">
              <i class="iconfont2 icon-text" />
              <span>文本</span>
            </div>
            <div class="ep-draggable-item item" tid="defaultModule.image">
              <i class="iconfont2 icon-tupian-filled" />
              <span>图片</span>
            </div>
            <div class="ep-draggable-item item" tid="defaultModule.longText">
              <i class="iconfont2 icon-icon-test" />
              <span>长文</span>
            </div>
            <div class="ep-draggable-item item" tid="defaultModule.table">
              <i class="iconfont2 icon-biaoge" />
              <span>表格</span>
            </div>
            <div class="ep-draggable-item item" tid="defaultModule.emptyTable">
              <i class="iconfont2 icon-kongbiaoge" />
              <span>空表格</span>
            </div>
            <div class="ep-draggable-item item" tid="defaultModule.html">
              <i class="iconfont2 icon-html" />
              <span>HTML</span>
            </div>
            <div class="ep-draggable-item item" tid="defaultModule.customText">
              <i class="iconfont2 icon-zidingyi" />
              <span>自定义</span>
            </div>
            <div class="ep-draggable-item item" tid="defaultModule.hline">
              <i class="iconfont2 icon-hengxian" />
              <span>横线</span>
            </div>
            <div class="ep-draggable-item item" tid="defaultModule.vline">
              <i class="iconfont2 icon-shuxian" />
              <span>竖线</span>
            </div>
            <div class="ep-draggable-item item" tid="defaultModule.rect">
              <i class="iconfont2 icon-juxing" />
              <span>矩形</span>
            </div>
            <div class="ep-draggable-item item" tid="defaultModule.oval">
              <i class="iconfont2 icon-yuanxingweixuanzhong" />
              <span>圆形</span>
            </div>
            <div class="ep-draggable-item item" tid="defaultModule.barcode">
              <i class="iconfont2 icon-saoma" />
              <span>条形码</span>
            </div>
            <div class="ep-draggable-item item" tid="defaultModule.qrcode">
              <i class="iconfont2 icon-erweima" />
              <span>条形码</span>
            </div>
          </el-space>
          <div id="provider-container" class="provider-box"></div>
        </pane>
        <pane :size="60" class="card pane-box">
          <div class="container">
            <div id="hiprint-printTemplate"></div>
          </div>
        </pane>
        <pane :size="25" class="card pane-box">
          <div class="left">
            <div id="PrintElementOptionSetting"></div>
          </div>
        </pane>
      </splitpanes>
    </div>
    <JsonPreview :template="jsonTemplate" ref="jsonPreviewRef" />
    <JsonImport :template="jsonTemplate" ref="jsonImportRef" />
    <PrintPreview ref="printPreviewRef" />
  </div>
</template>

<script setup name="Print">
import { ZoomIn, ZoomOut, CircleClose, Refresh, View, Printer, Download } from '@element-plus/icons-vue';
import { onMounted, ref ,nextTick } from 'vue';
import { hiprint, defaultElementTypeProvider } from 'vue-plugin-hiprint';
import { newHiprintPrintTemplate } from '@/utils/template-helper';
import { usePaper } from '@/hooks/use-paper';
import { useZoom } from '@/hooks/use-zoom';
import provider from './provider';
import { Splitpanes, Pane } from 'splitpanes';
import 'splitpanes/dist/splitpanes.css';
import JsonPreview from './components/JsonPreview.vue';
import JsonImport from './components/JsonImport.vue';
import PrintPreview from './components/PrintPreview.vue';
import { printConfig } from './config';
import { useRoute } from 'vue-router';
import {getPrintTemplate,savePrintTemplate} from "@/api/modules/toolbox/print"
import {  ElMessage,ElMessageBox  } from 'element-plus';
const { paperTypes, curPaperType, paperWidth, paperHeight, showPaperPop, setPaper, setPaperOther } = usePaper();
const { scaleValue, changeScale } = useZoom();
const jsonPreviewRef = ref(null);
const jsonTemplate = ref(null);
const jsonImportRef = ref(null);
const printPreviewRef = ref(null);
let hiprintTemplate;
const route = useRoute();
const dataTemplate = ref({});
onMounted(async() => {
  const { data } = await getPrintTemplate(route.query);
  if (data.template) {
    dataTemplate.value = JSON.parse(data.template);
  }
  nextTick(() => {
  init();
  buildLeftElement();
  buildDesigner(dataTemplate.value);
  })
  
});
// 初始化元素
const init = () => {
  hiprint.init({
    providers: [defaultElementTypeProvider(), provider]
  });
};

const buildLeftElement = () => {
  hiprint.PrintElementTypeManager.build($('#provider-container'), 'taskProviderModule');
  hiprint.PrintElementTypeManager.buildByHtml($('.ep-draggable-item'));
};

const buildDesigner = (template) => {
  $('#hiprint-printTemplate').empty();
  jsonTemplate.value = hiprintTemplate = newHiprintPrintTemplate({
    template: template,
    settingContainer: '#PrintElementOptionSetting',
    ...printConfig
  });
  hiprintTemplate.design('#hiprint-printTemplate');
};

//保存
const handleSaveTemplate = () => {
  ElMessageBox.confirm(
    '保存操作会覆盖当前模板，是否继续？',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async() => {
      const json = jsonTemplate.value.getJson();
  await savePrintTemplate({
    id: route.query.id,
    template: JSON.stringify(json)
  });
  ElMessage.success({ message: `保存模板成功！` });
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消保存',
      })
    })
  
  
 
}

//打印预览
const print = () => {
  printPreviewRef.value.show(jsonTemplate.value.getJson());
};

//旋转纸张
const rotatePaper = () => {
  hiprintTemplate.rotatePaper();
};
//清空所有元素
const clearPaper = () => {
  hiprintTemplate.clear();
};
//查看json
const jsonView = () => {
  jsonPreviewRef.value.show();
};
// json导入
const jsonImport = () => {
  jsonImportRef.value.show();
};
//设置元素对齐方式
const setElsAlign = e => {
  hiprintTemplate.setElsAlign(e);
};
</script>

<style lang="scss">
@import '@/styles/var.scss';
/* 重写全局 hiprint 样式 */
.hiprint-headerLine,
.hiprint-footerLine {
  border-color: purple !important;
}

.hiprint-headerLine:hover,
.hiprint-footerLine:hover {
  border-top: 3px dashed purple !important;
}

.hiprint-headerLine:hover:before {
  content: '页眉线';
  left: calc(50% - 18px);
  position: relative;
  background: #ffff;
  top: -14px;
  color: purple;
  font-size: 12px;
}

.hiprint-footerLine:hover:before {
  content: '页脚线';
  left: calc(50% - 18px);
  position: relative;
  color: purple;
  background: #ffff;
  top: -14px;
  font-size: 12px;
}
.splitpanes--vertical > .splitpanes__splitter {
  background: transparent;
  position: relative;
  margin: 0 3px;

  &::before,
  &::after {
    content: '';
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    width: 1px;
    height: 30px;
    background-color: var(--el-color-primary);
    border-radius: 2px;
    transition: background-color 0.3s;
  }

  &::before {
    left: calc(50% - 2px);
  }

  &::after {
    left: calc(50% + 2px);

    &:hover::before,
    &:hover::after {
      background-color: var(--el-color-primary-light-3);
    }
  }
}

.provider-box {
  .hiprint-printElement-type {
    width: 100%;
    display: block;
    padding: 0 0 0 0;
    li {
      list-style: none;
    }
  }

  li {
    .title {
      display: block;
      font-size: $el-text-font-size;
      align-self: center;
      color: $el-text-color-regular;
      overflow-wrap: break-word;
      padding: 0;
      font-weight: bolder;
      margin-bottom: 20px;
    }
    ul {
      display: flex;
      justify-content: space-around;
      flex-wrap: wrap;
      padding: 0;

      li {
        display: flex;
        width: 50%;
        justify-content: center;
        align-items: center;
        a {
          padding: 12px 6px;
          color: $primary-color;
          text-decoration: none;
          margin-right: 5px;
          display: inline-block;
          text-align: center;
          margin-bottom: 5px;
          box-sizing: border-box;
          font-size: 14px;
        }
      }
    }
  }
}
</style>
<style scoped lang="scss">
@import './index.scss';
</style>
